<?php
App::uses('AppModel', 'Model');
/**
 * Customer Model
 *
 * @property Gender $Gender
 * @property Group $Group
 */
class Customer extends AppModel {


	//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * belongsTo associations
 *
 * @var array
 */
        var $actAs = array('Searchable');
        
        public $validate = array(
                'first_name' => array(
                        'noempty' => array(
                                'rule' => 'notEmpty',
                                'message' => 'Please enter your first name',
                                'required' => 'create',
                        ),

                ),
                'last_name' => array(
                        'noempty' => array(
                                'rule' => 'notEmpty',
                                'message' => 'Please enter your last name',
                                'required' => 'create',
                        ),
                ),
                'dob' => array(
                        'noempty' => array(
                                'rule' => 'notEmpty',
                                'message' => 'Please enter your date of birth',
                                'required' => 'create',
                        ),
                ),
                'gender_id' => array(
                        'noempty' => array(
                                'rule' => 'notEmpty',
                                'message' => 'Please enter your gender',
                                'required' => 'create',
                        ),
                ),
                /*'postcode' => array(
                        'postcode' => array(
                                'rule' => array('postal', null, 'au'),   
                        ),
                ),*/
                /*'phone' => array(
                        'phone' => array(
                                'rule' => array('phone', null, 'all'),
                        ),
                ),*/
                /*'join_date' => array(
                        'join_date' => array(
                                'rule' => array('date', 'dmy'),
                                'message' => 'Please enter a valid date in DD-MM-YYYY format',
                        ),
                ),*/
                'username' => array(
			'notempty' => array(
				'rule' => 'notEmpty',
				'message' => 'Please choose your username',
			),
                        'unique' => array(
                                'rule' => array('isUnique'),
                                'message' => 'Username already in use',
                        ),
		),
                //password_current: replacement for password in reset password form
                'password_current' => array(
			'notempty' => array(
				'rule' => 'notEmpty',
				'message' => 'Please enter your password',
			),
                        'is_current' => array(
                                'rule' => 'is_current',
                                'message' => 'Please enter your current password',
                        ),
		),
		'password' => array(
			'notempty' => array(
				'rule' => 'notEmpty',
				'message' => 'Please enter your password',
			),
		),
                'confirm_password' => array(
                        'noempty' => array(
                                'rule' => 'notEmpty',
                                'message' => 'Please enter your password again',
                        ),
                        'is_matched' => array(
                                'rule' => 'matchPassword',
                                'message' => 'Passwords do not match',
                        ),
                ),
                //new password for reset in reset password form
                'password_new' => array(
			'notempty' => array(
				'rule' => 'notEmpty',
				'message' => 'Please enter your password',
			),
		),
                'confirm_password_new' => array(
                        'noempty' => array(
                                'rule' => 'notEmpty',
                                'message' => 'Please enter your password again',
                        ),
                        'is_matched' => array(
                                'rule' => 'matchPasswordNew',
                                'message' => 'Passwords do not match',
                        ),
                ),
                'email' => array(
                        'email' => array(
                                'rule' => array('email', true),
                                'message' => 'Please enter a valid email address',
                        ),
                    'unique' => array(
                        'rule' => array('isUnique'),
                        'message' => 'Email is already registered',
                    ),
                ),
                //captcha for validate captcha in add form
                'captcha'=>array(
                        'noempty' => array(
                                'rule' => array('notEmpty'),
                                'message' => 'Please verify you are human',
                        ),
                        'matchCaptcha' => array(
				'rule' => array('matchCaptcha'),
				'message'=>'Failed validating human check',
                        ),
		),
	);
	public $belongsTo = array(
		'Gender' => array(
			'className' => 'Gender',
			'foreignKey' => 'gender_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Group' => array(
			'className' => 'Group',
			'foreignKey' => 'group_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
	);

    public $hasMany = array(
        'Sale' => array(
            'className' => 'Sale',
            'foreignKey' => 'customer_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),

        'Order' => array(
            'className' => 'Order',
            'foreignKey' => 'customer_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

        
//---------------------- Custom function --------------------------------------
        
        //-------------- Check to see if password and confirm_password match
        public function matchPassword($data) {
            if ($data['confirm_password'] == $this->data['Customer']['password'])
            {
                return true;
            }
            $this->invalidate('password', 'Passwords do not match');
            return false;
        }
        
        //-------------- Check password_new and confirm_password_new matches
        public function matchPasswordNew($data) {
            if ($data['confirm_password_new'] == $this->data['Customer']['password_new'])
            {
                return true;
            }
            $this->invalidate('password_new', 'Passwords do not match');
            return false;
        }
        
        //-------------- Check to see if password_current in reset password form
        //-------------- is current --------------------------------------------
        public function is_current($data) {
            $this->id = AuthComponent::user('id');
            $inputPassword = $this->field('password');
            return (AuthComponent::password($data['password_current']) == $inputPassword);
        }
        
        //-------------- Hash password before saving
        public function beforeSave($options = array()) {
            if (isset($this->data['Customer']['password'])) {
                $this->data['Customer']['password'] = AuthComponent::password($this->data['Customer']['password']);
            }
            
            if (isset($this->data['Customer']['password_new'])) {
                $this->data['Customer']['password'] = AuthComponent::password($this->data['Customer']['password_new']);
            }
            
            return true;
        }
        
        /*public function getActivationHash() {
            if (!isset($this->data['Customer']['id'])) {
                return false;
            }
            return AuthComponent::password($this->data['Customer']['email']);
        }*/
        
        
        //-------------- Captcha related functions
        function matchCaptcha($inputValue)	{
		return $inputValue['captcha']==$this->getCaptcha(); //return true or false after comparing submitted value with set value of captcha
	}

	function setCaptcha($value)	{
		$this->captcha = $value; //setting captcha value
	}

	function getCaptcha()	{
		return $this->captcha; //getting captcha value
	}
        
	public function GetData() {
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* Easy set variables
	*/
	
	/* Array of database columns which should be read and sent back to DataTables. Use a space where
	* you want to insert a non-database field (for example a counter or static image)
	*/
	$aColumns = array( 'id', 'first_name', 'last_name', 'username', 'email' );
	
	/* Indexed column (used for fast and accurate table cardinality) */
	$sIndexColumn = "id";
	
	/* DB table to use */
	$sTable = "customers";
	
	
	 App::uses('ConnectionManager', 'Model');
        $dataSource = ConnectionManager::getDataSource('default');
         
        /* Database connection information */
        $gaSql['user']       = $dataSource->config['login'];
        $gaSql['password']   = $dataSource->config['password'];
        $gaSql['db']         = $dataSource->config['database'];
        $gaSql['server']     = $dataSource->config['host'];
         
         
        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         * If you just want to use the basic configuration for DataTables with PHP server-side, there is
        * no need to edit below this line
        */
         
        /*
         * Local functions
        */
        function fatal_error ( $sErrorMessage = '' )
        {
            header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );
            die( $sErrorMessage );
        }
         
         
        /*
         * MySQL connection
        */
        if ( ! $gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) )
        {
            fatal_error( 'Could not open connection to server' );
        }
         
        if ( ! mysql_select_db( $gaSql['db'], $gaSql['link'] ) )
        {
            fatal_error( 'Could not select database ' );
        }
         
         
        /*
         * Paging
        */
        $sLimit = "";
        if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
        {
            $sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] ).", ".
                    intval( $_GET['iDisplayLength'] );
        }
         
         
        /*
         * Ordering
        */
        $sOrder = "";
        if ( isset( $_GET['iSortCol_0'] ) )
        {
            $sOrder = "ORDER BY  ";
            for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
            {
                if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
                {
                    $sOrder .= "`".$aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."` ".
                        ($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc') .", ";
                }
            }
         
            $sOrder = substr_replace( $sOrder, "", -2 );
            if ( $sOrder == "ORDER BY" )
            {
                $sOrder = "";
            }
        }
         
         
        /*
         * Filtering
        * NOTE this does not match the built-in DataTables filtering which does it
        * word by word on any field. It's possible to do here, but concerned about efficiency
        * on very large tables, and MySQL's regex functionality is very limited
        */
        $sWhere = "";
        if ( isset($_GET['sSearch']) && $_GET['sSearch'] != "" )
        {
            $sWhere = "WHERE (";
            for ( $i=0 ; $i<count($aColumns) ; $i++ )
            {
                $sWhere .= "`".$aColumns[$i]."` LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
            }
            $sWhere = substr_replace( $sWhere, "", -3 );
            $sWhere .= ')';
        }
         
        /* Individual column filtering */
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
            {
                if ( $sWhere == "" )
                {
                    $sWhere = "WHERE ";
                }
                else
                {
                    $sWhere .= " AND ";
                }
                $sWhere .= "`".$aColumns[$i]."` LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
            }
        }
         
         
        /*
         * SQL queries
        * Get data to display
        */
        $sQuery = "
    SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", implode("`, `", $aColumns))."`
            FROM   $sTable
            $sWhere
            $sOrder
            $sLimit
            ";
        $rResult = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
         
        /* Data set length after filtering */
        $sQuery = "
    SELECT FOUND_ROWS()
";
        $rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
        $aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
        $iFilteredTotal = $aResultFilterTotal[0];
         
        /* Total data set length */
        $sQuery = "
    SELECT COUNT(`".$sIndexColumn."`)
            FROM   $sTable
            ";
        $rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
        $aResultTotal = mysql_fetch_array($rResultTotal);
        $iTotal = $aResultTotal[0];
         
         
        /*
         * Output 
        */
        $output = array(
                "sEcho" => intval($_GET['sEcho']),
                "iTotalRecords" => $iTotal,
                "iTotalDisplayRecords" => $iFilteredTotal,
                "aaData" => array()
        );
		
        while ( $aRow = mysql_fetch_array( $rResult ) )
        {
            $row = array();
            for ( $i=0 ; $i<count($aColumns) ; $i++ )
            {
                if ( $aColumns[$i] == "version" )
                {
                    /* Special output formatting for 'version' column */
                    $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
			
			
                }
                else if ( $aColumns[$i] != ' ' )
                {
                    /* General output */
                    $row[] = $aRow[ $aColumns[$i] ];		
                }
				$actionid = $aRow[ $aColumns[0] ];
            }

			$row[] = '<div class="action"><a href="Customers/view/'.$actionid.'">View</a><a href="Customers/edit/'.$actionid.'">Edit</a> <form id="post_'.$actionid.'" method="post" style="display:none;" name="post_'.$actionid.'" action="Customers/delete/'.$actionid.'"></form><a href="#" onclick="if (confirm(\'Are you sure you want to delete # '.$actionid.'?\')) { document.post_'.$actionid.'.submit(); } event.returnValue = false; return false;">Delete</a> <a href="Customers/resetPassword/'.$actionid.'">Reset Password</a></div>';
			
            $output['aaData'][] = $row;
        }
         
        return $output;
    }	
	
	function getorders($oId)
	{	
		App::uses('ConnectionManager', 'Model');
        $dataSource = ConnectionManager::getDataSource('default');
         
        /* Database connection information */
        $gaSql['user']       = $dataSource->config['login'];
        $gaSql['password']   = $dataSource->config['password'];
        $gaSql['db']         = $dataSource->config['database'];
        $gaSql['server']     = $dataSource->config['host'];
 		$gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  );
		mysql_select_db( $gaSql['db'], $gaSql['link'] );
			
		$sRes = mysql_query("select o.id,o.created,d.tracking,ds.name,o.total from deliveries d left join orders o on o.id = d.order_id 
							left join delivery_statuses ds on ds.id = d.delivery_status_id 
							where o.customer_id = '".$oId."'", $gaSql['link'] );
		$sRowVal = array();
		while($sRow = mysql_fetch_array( $sRes ))
		{
			$sRowVal[] = $sRow ;
		}
		
		return $sRowVal;	
	}	
	
	function createTempPassword($len) {
	   $pass = '';
	   $lchar = 0;
	   $char = 0;
	   for($i = 0; $i < $len; $i++) {
		 while($char == $lchar) {
		   $char = rand(48, 109);
		   if($char > 57) $char += 7;
		   if($char > 90) $char += 6;
		 }
	
	
		 $pass .= chr($char);
		 $lchar = $char;
	   }
	
	
	   return $pass;
	}
}
